var oper = getQueryString('oper')
var flowId = getQueryString('flowId')

//全局js值保存。
var menuCopyType; //ztree复制节点的页面类型
var menuCopyNodes; //ztree复制节点临时存储

var queryPktListTreeUrl = "/comm/syscommflow/createTree";


var baseUrl = '/pages/pre/msg/type/'
var typeConfig = {
  'RECV': {
    url: baseUrl + 'policyEdit',
    label: '通迅接入',
  },
  'UNPACKHD': {
    url: baseUrl + 'fieldEdit',
    label: '解包报文头'
  },
  'UNPACK': {
    url: baseUrl + 'loopEdit',
    label: '解包报文'
  },
  'PACK': {
    url: baseUrl + 'structEdit',
    label: '报文组包'
  },
  'SEND': {
    url: baseUrl + 'switchEdit',
    label: '发送报文'
  },
  'RCVASYNC': {
    url: baseUrl + 'defaultEdit',
    label: '接出的异步应答'
  },
  'RETATTR': {
    url: baseUrl + 'caseEdit',
    label: '设置返回属性'
  },
  'SNDYFA': {
    url: baseUrl + 'caseEdit',
    label: 'YFA调用'
  },
  'EXTCALL': {
    url: baseUrl + 'caseEdit',
    label: '插件调用'
  },
  'RESTCALL': {
    url: baseUrl + 'caseEdit',
    label: 'Rest服务调用'
  },
  'RESTIPCALL':{
    url: baseUrl + 'caseEdit.html',
    label: 'RestIP调用'
}
}

var saveCfg = api + "/comm/syscommflow";
var pktSelectNode;
var zTree;
var treeNode;
var rMenu;
var nodeTid;


var addList = [{
  label: '通迅接入',
  value: 'RECV'
}, {
  label: '解包报文头',
  value: 'UNPACKHD'
}, {
  label: '解包报文',
  value: 'UNPACK'
}, {
  label: '报文组包',
  value: 'PACK'
}, {
  label: '发送报文',
  value: 'SEND'
}, {
  label: '接出的异步应答',
  value: 'RCVASYNC'
}, {
  label: '设置返回属性',
  value: 'RETATTR'
}, {
  label: 'YFA调用',
  value: 'SNDYFA'
}, {
  label: '插件调用',
  value: 'EXTCALL'
},{
   value: 'RESTCALL',
   label: 'Rest服务调用'
  },{
   value: 'RESTIPCALL',
   label: 'RestIP调用'
}]

// 初始化树的配置信息
var setting = {
  edit: {
    drag: {
      autoExpandTrigger: true,
      prev: true,
      inner: false,
      next: true,
      isCopy: false,
      isMove: true
    },
    enable: true,
    showRemoveBtn: false,
    showRenameBtn: false
  },
  data: {
    key: {
      children: "children",
      name: "label"
    }
  },
  callback: {
    onClick: addConfigModel,
    onRightClick: OnPktRightClick,
    beforeDrag: beforeDrag
  }
};

var rule = {
  transCode: {
    required: true
  }
};

var message = {
  transCode: {
    required: "请输交易码"
  }
};


$(function () {
	var groupAll=[];
  getInsystem()

  $('#pktnode_div .form-group').hide()

  if (oper === 'edit' || oper === 'view') {
    getDetail()
  }
  $.common.initFormInfo();


  bindEvents();

  //初始化复制选项页面信息
  if ("pktEdit" != menuCopyType) {
    menuCopyType = "pktEdit";
    menuCopyNodes = null;
  }


});


function getDetail(id) {
  var data = {
    flowId: flowId,
    sysCode: getQueryString('systemCode'),
    groupCode: getQueryString('groupCode'),
    transCode: getQueryString('transCode')
  }
  $('#pkt_transCode_txt').val(data.transCode)
  getGroup(data.sysCode)
  groupCodeAndOut(data.sysCode);
  getserversList();
  createAjax(data)

}

//获取接入项目列表
function getInsystem() {
  $.operate.get(api + '/comm/insystem/insys_list', function (res) {
    res.data.forEach(function (item) {
      if (getQueryString('systemCode') && getQueryString('systemCode') == item.code) {
        $("#pkt_systemCode_select").append("<option selected='selected' value=" + item.code + ">" + item.name + "</option>");
      } else {
        $('#pkt_systemCode_select').append('<option value="' + item.code + '">' + item.name + '</option>')
      }

    })
  }, false)
}
//获取服务列表 server_select
function getserversList() {
  $('#server_select').find('option').remove()
  $.operate.post(api + '/comm/syscommflow/nacosServiers',{}, function (res) {
    res.data.forEach(function (item) {
        $('#server_select').append('<option value="' + item + '">' + item + '</option>')
    })
  }, false)
}
//获取项目列表
function groupCodeAndOut(code) {
  $.operate.get(api + '/comm/group/group_list/groupCodeAndOut/'+ code, function (res) {
	 groupAll=res.data
     groupAll.forEach(function (item) {
      if (getQueryString('groupCode') && getQueryString('groupCode') == item.code) {
        $("#node_group_select").append("<option selected='selected' value=" + item.code + ">" + item.name + "</option>");
      } else {
        $('#node_group_select').append('<option value="' + item.code + '">' + item.name + '</option>')
      }
    })
  }, false)
}
//根据接入项目名称获取服务列表
function getGroup(code) {
  $('#pkt_groupCode_select').find('option').remove()
  $.operate.get(api + '/comm/group/group_list/code/' + code, function (res) {
    res.data.forEach(function (item) {
      if (getQueryString('groupCode') && getQueryString('groupCode') == item.code) {
        $("#pkt_groupCode_select").append("<option selected='selected' value=" + item.code + ">" + item.name + "</option>");
      } else {
        $('#pkt_groupCode_select').append('<option value="' + item.code + '">' + item.name + '</option>')
      }
    })
  }, false)
}


//查询树
function queryPktListFunc() {
  if ($("#pktConditionForm").valid()) {

    $('#pktnode_div .form-group').hide()
    var data = {}
    data.sysCode = $("#pkt_systemCode_select").val();
    data.groupCode = $("#pkt_groupCode_select").val();
    data.transCode = $("#pkt_transCode_txt").val()
    createAjax(data)

    addDefaultValue()
  }

}

function createAjax(data) {
  $.ajax({
    url: queryPktListTreeUrl,
    type: "POST",
    contentType: 'application/json;charset=utf-8', // 设置请求头信息
    dataType: "json",
    data: JSON.stringify(data), // 将Json对象序列化成Json字符串，JSON.stringify()原生态方法
    // data: $.toJSON(node),
    // //将Json对象序列化成Json字符串，toJSON()需要引用jquery.json.min.js
    success: function (res) {
      var treeData = []
      var sysName = $("#pkt_systemCode_select").find("option:selected").text()
      if (res.data == null || res.data.content == null) {
        // this.searchData.pktId = null
        var configName = data.sysCode + "." + data.groupCode + "." + data.transCode + ".流程配置"
        treeData = [{
          "id": 0,
          "label": configName,
          "children": [
            {
            "id": 3,
            "label": "解包报文",
            "children": [],
            "dataModel": {
              "systemId": data.sysCode,
              "group": data.groupCode,
              "inParam": "",
              "outParam": "",
              "transCode": data.transCode,
              "recvField": null,
              "inDict": null,
              "type": "UNPACK"
            },
            "dropInner": false,
            "type": "UNPACK",
          }, {
            "id": 9,
            "label": "YFA调用",
            "children": [],
            "dataModel": {
              "group": data.groupCode,
              "inParam": "",
              "outParam": "",
              "transCode": data.transCode,
              "type": "SNDYFA"
            },
            "dropInner": false,
            "type": "SNDYFA",
          }, {
            "id": 4,
            "label": "报文组包",
            "children": [],
            "dataModel": {
              "systemId": data.sysCode,
              "group": data.groupCode,
              "inParam": "",
              "outParam": "",
              "transCode": data.transCode,
              "recvField": null,
              "inDict": null,
              "type": "PACK"
            },
            "dropInner": false,
            "type": "PACK",
          }, {
            "id": 5,
            "label": "发送报文",
            "children": [],
            "dataModel": {
              "systemId": data.sysCode,
              "group": data.groupCode,
              "inParam": "",
              "outParam": "",
              "transCode": data.transCode,
              "recvField": "",
              "inDict": "",
              "type": "SEND"
            },
            "dropInner": false,
            "type": "SEND",
          }],
          "dropInner": true,
          "root": false,
          "type": null
        }]

      } else {
        flowId = res.data.flowId
        treeData = res.data.content
      }

      $.fn.zTree.init($("#pktList_treeview"), setting, treeData);
      zTree = $.fn.zTree.getZTreeObj("pktList_treeview");
      rMenu = $("#rMenu");
    }
  });
}

/**
 * 创建请求参数
 */
function createRequestParam(node) {
  var systemCode;
  var groupCode;
  systemCode = $("#pkt_systemCode_select").val();
  groupCode = $("#pkt_groupCode_select").val();
  var transCode = $("#pkt_transCode_txt").val();
  return {
    flowId: flowId,
    "systemCode": systemCode,
    "groupCode": groupCode,
    "transCode": transCode,
    "data": node
  }
}


function bindEvents() {
  $("#pkt_systemCode_select").bind('change', function () {
    $("#pkt_groupCode_select").empty();
    var sysId = $("#pkt_systemCode_select").val()
    getGroup(sysId)
  });

  $("#pkt_groupCode_select").bind('change', function () {
    queryPktListFunc();
  });
  
  $("#node_group_select").bind('change', function () {
	  var groupCode = $("#pkt_groupCode_select").val();
	  var now=$(this).val();
	  var g=groupAll.find( (item) => item.code == now);
	  if (g.flag === 'inSys'){
	    $("#sysNameTxt").val('')
	  }else{
		var sysCode = $("#pkt_systemCode_select").val()
		$("#sysNameTxt").val(sysCode)
	  }
  });

  //保存报文配置
  $("#savePktTree").bind("click", function () {
    if ($("#pktList_treeview").html().trim() == "") {
      $.modal.msgError("保存失败，请正确加载界面信息！");
      return;
    }
    try {
      var node = zTree.getNodeByTId("treeview_1");
      var requestParam = createRequestParam(node);
      var parent = window.parent
      $.ajax({
        url: saveCfg,
        type: flowId ? "PUT" : "POST",
        contentType: 'application/json;charset=utf-8', // 设置请求头信息
        dataType: "json",
        data: JSON.stringify(requestParam), // 将Json对象序列化成Json字符串，JSON.stringify()原生态方法
        // data: $.toJSON(node),
        // //将Json对象序列化成Json字符串，toJSON()需要引用jquery.json.min.js
        success: function (result) {
          if (result.data) {
            $.modal.close()
            parent.$.modal.msgSuccess('保存成功');
            parent.$.table.refresh();
          } else {
            $.modal.msgError("保存失败！");
          }
        }
      });
    } catch (e) {
      console.log(e);
      $.modal.msgError("保存失败！");
    }
  });

}


function filter(node) {
  return (node.type != null);
}

function error(d) {
  $.modal.msgError(d.message);
}

function addRootTreeNode(type) {
  hideRMenu();
  var name = typeConfig[type].label;

  var newNode = {
    label: name,
    type: type,
    value: type,
  };
  zTree.addNodes(zTree.getNodeByTId("treeview_1"), newNode);
}


function beforeDrag(treeId, treeNodes) {
  for (var i = 0, l = treeNodes.length; i < l; i++) {
    if (treeNodes[i].drag === false) {
      curDragNodes = null;
      return false;
    } else if (treeNodes[i].parentTId
      && treeNodes[i].getParentNode().childDrag === false) {
      curDragNodes = null;
      return false;
    }
  }
  curDragNodes = treeNodes;
  return true;
}

/**
 * 单击节点添加属性
 */
function addConfigModel(event, treeId, treeNode, clickFlag) {
  pktSelectNode = treeNode;
  nodeTid = treeNode.tId;
  $("#pktnode_div .form-group").each(function(item){
    var dataType = $(this).data('type')
    var typeList = dataType ? dataType.split('-') : []
    if (typeList.indexOf(treeNode.type) != -1) {
      $(this).show()
      $(this).find('.form-control').val('')
      $(this).find('.form-control').removeAttr("disabled");
    }else{
      $(this).hide()
      $(this).find('.form-control').val('')
      $(this).find('.form-control').attr("disabled", "disabled");
    }
  })
  if (treeNode.type === 'SNDYFA'){
    $('#transCode_title').text('YFA交易码')
  }else{
    $('#transCode_title').text('交易码')
  }
  $('#allTypeShow').show()
  addDefaultValue(treeNode)

}

/**
 * 添加默认值
 *
 * @returns {String}
 */

function addDefaultValue(treeNode) {

  $('#sysNameTxt').val($("#pkt_systemCode_select").val())
  $('#node_group_select').val($("#pkt_groupCode_select").val())
  $('#transCodeTxt').val($("#pkt_transCode_txt").val())

  if (treeNode) {
    var dataModel = treeNode.dataModel ? treeNode.dataModel : {}
    $('#typeTxt').val(treeNode.label);
    $('#typeCodeTxt').val(treeNode.type)
    $("#root_desc").val(treeNode.getParentNode().label);
    applyDrawing('#pkt_node_configForm', dataModel)
  }


/*

  var sysId = $("#systemCode_select").val();
  if (sysId == "-1") {
    return "SYS_MIS";
  }
  var groupCode = $("#groupCode_select").val();
  if (groupCode == "-1") {
    return "GRP_MIS";
  }
*/




}

//点击新增节点
function addNodeSelect() {
  $('#dropdown-menu').show()
}

// 删除节点
function removeTreeNode() {
  hideRMenu();
  var nodes = zTree.getSelectedNodes();
  if (pktSelectNode.children && pktSelectNode.children.length > 0) {
    $.modal.confirm('要删除的节点是父节点，如果删除将连同子节点一起删掉。是否确认删除该节点？', function () {
      zTree.removeNode(pktSelectNode);
    })

  } else {
    $.modal.confirm('是否确认删除该节点？', function () {
      zTree.removeNode(pktSelectNode);
    })
  }
}

// 复制节点
function copyTreeNode() {
  // menuCopyNodes = zTree.getSelectedNodes();
  menuCopyNodes = pktSelectNode
  hideRMenu();
  $('#pktnode_div .form-group').hide()
}

//粘贴节点
function postTreeNode() {
  if (null != menuCopyNodes) {
    zTree.addNodes(zTree.getNodeByTId("treeview_1"), menuCopyNodes);
    menuCopyNodes = null;
  } else {
    $.modal.msgError("请选择需要复制的节点！");
  }
  hideRMenu();
}

//剪切节点
function cutTreeNode() {
  // menuCopyNodes = zTree.getSelectedNodes();
  // zTree.removeNode(menuCopyNodes[0]);
  menuCopyNodes = pktSelectNode;
  zTree.removeNode(menuCopyNodes);
  hideRMenu();
  $('#pktnode_div .form-group').hide()
}

// 右键菜单加载
function OnPktRightClick(event, treeId, treeNode) {
  if (treeNode.root) return
  $('#dropdown-menu').empty()
  pktSelectNode = treeNode
  addList.forEach(function (item) {
    $('#dropdown-menu').append('<li onclick="addRootTreeNode(\'' + item.value + '\')"><a tabindex="-1">' + item.label + '</a></li>')
  })
  $("#dropdown-menu").css({
    "position": "absolute",
    "top": "-2px",
    "left": "100%",
    "height": "100%",
    "overflow": 'auto',
    'display': 'none'
  });

  $("#rMenu #dropdown-menu-parent").show();
  var y = event.clientY
  var x = event.clientX
  y += $(window).scrollTop() ;
  x += document.body.scrollLeft;
  rMenu.css({
    "top": y + "px",
    "left": x + "px",
    "visibility": "visible"
  });

  $("body").bind("mousedown", onBodyMouseDown);


}

function onBodyMouseDown(event) {
  if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
    rMenu.css({
      "visibility": "hidden"
    });
  }
}


function hideRMenu() {
  if (rMenu)
    rMenu.css({
      "visibility": "hidden"
    });
  $("body").unbind("mousedown", onBodyMouseDown);
}

/**
 * 保存节点配置
 */
function saveNodeInfo() {
  var divIsEmpty = $("#pktnode_div").html().trim();
  if ("" == divIsEmpty || divIsEmpty.length == 0) {
    return;
  }
  if ($("#pkt_node_configForm").valid()) {
    //保存前做额外的定制化判断 tag 长度必须大于2且最后一字符必须为字母

    var data = $('#pkt_node_configForm').serializeObject()

    pktSelectNode.dataModel = data;
    pktSelectNode.formData = data;
    zTree.refresh();
    $.modal.msgSuccess('保存成功！')


  }

}

//子节点获取报文类型，勿删！！！！！！！！！！！其他页面有用到此方法
function getPolicyType(data) {
  var targetNode = data.getParentNode()
  if (targetNode.pktType === 'policy') {
    return targetNode.dataModel ? targetNode.dataModel.type : ''
  } else {
    return getPolicyType(targetNode)
  }
}